package agents.model;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import weka.core.Instances;
import agents.behaviours.DataServiceBehaviour;
import jade.core.Agent;
import jade.core.Location;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.wrapper.ControllerException;

public class DataServiceAgent extends Agent {

	
	public static final String SERVICE_NAME= "DATA_SOURCE";
	
	private String dataPath = null;
	
	private Instances data;
	
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void setup() {
		super.setup();
		Object[] args = getArguments();
		if(args.length == 0){
			throw new RuntimeException("You must specify the path for data source");
		}
		dataPath = args[0].toString();
		if(!dataPath.endsWith(".arff")){
			throw new RuntimeException("Only .arff formats supported");
		}
		try {
			FileReader reader = new FileReader(dataPath);
			data = new Instances(reader);
			
		} catch (FileNotFoundException e) {
			throw new RuntimeException("The file does not exist!");
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		
		DFAgentDescription dfad = new DFAgentDescription();
		dfad.setName(getAID());
		ServiceDescription sd = new ServiceDescription();
		sd.setName(SERVICE_NAME);
		try {
			sd.setType(getContainerController().getContainerName()); // the service type is the name of the container
			dfad.addServices(sd);
			DFService.register(this, dfad); // register service
		} catch (FIPAException e) {
			throw new RuntimeException(e);
		} catch (ControllerException e) {
			throw new RuntimeException(e);
		}
		addBehaviour(new DataServiceBehaviour());
		
	}
	
	@Override
	public void doClone(Location arg0, String arg1) {
		throw new RuntimeException("Data service agent cannot be clone!");
	}
	
	@Override
	public void doMove(Location loc) {
		throw new RuntimeException("Data service agent cannot be moved!");
	}
	

	@Override
	protected void takeDown() {
		super.takeDown();
		
		try {
			DFService.deregister(this);
		} catch (FIPAException e) {
			throw new RuntimeException(e);
		}
		
	}

	public Instances getData() {
		return data;
	}

	
	
	
}
